<template>
  <div>
    <div style="margin-bottom:10px;padding-bottom:6px;line-height:26px;white-space: nowrap;overflow-x:scroll;"
         class="beautiful-bar-h" v-if="tagShow">
      <template v-if="!value.length">
        <Tag>已选：</Tag>
        <Tag color="warning">无</Tag>
      </template>
      <template v-else>
        <Tag>已选：</Tag>
        <Tag v-for="item in value" :key="item.id" :name="item.id" closable @on-close="handleClose"
             :color="tagColor">
          {{ item[displayProperty] }}
        </Tag>
      </template>

    </div>

    <Form ref="queryForm">
      <Row :gutter="10">
        <Col span="24">
          <Input v-model="filter" :placeholder="placeholder" clearable icon="md-search" @on-click="handleSearch"
                 @on-enter="handleSearch" @on-clear="handleClear"></Input>
        </Col>
      </Row>
    </Form>

    <Table id="table_select" :columns="columns" no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" border
           :data="checkedItems" class="margin-top-10" @on-select="select" @on-select-cancel="selectCancel"
           @on-select-all="selectAll" @on-select-all-cancel="selectAllCancel" :loading="loading" ref="table"
           :highlight-row="!multiSelect" @on-row-click="rowClick" :row-class-name="rowClassName"
           @on-row-dblclick="rowDblClick" @on-cell-click="cellClick" @on-sort-change="sortChange">
    </Table>
    <Page show-sizer show-total :total="totalCount" class="margin-top-10" @on-change="pageChange"
          @on-page-size-change="pageSizeChange" :page-size="pageSize" :current="currentPage"
          :page-size-opts="[pageSize]">

    </Page>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';

@Component({
  components: {},
})
export default class TableSelectCommon extends AbpBase {
  name: string = 'TableSelectCommon';

  @Prop({type: Array, default: () => []}) value: any[];
  @Prop({type: Array, default: () => []}) columns: any[];
  @Prop({type: Array, default: () => []}) items: any[];
  @Prop({type: Number, default: 0}) totalCount: number;
  @Prop({type: Boolean, default: false}) tagShow: boolean;
  @Prop({type: Number, default: 10}) pageSize: number;
  @Prop({type: String, default: ''}) placeholder: string;
  @Prop({type: Number, default: 0}) connectId: number;
  @Prop({type: String, default: ''}) displayProperty: string;
  @Prop({type: String, default: 'warning'}) tagColor: string;
  @Prop({type: Boolean, default: false}) loading: boolean;

  @Prop({type: Array, default: () => []}) optional: any[];
  @Prop({type: Boolean, default: true}) multiSelect: boolean;


  currentPage: number = 1;
  filter: string = '';
  sorting: string = '';


  get checkedItems() {
    let temp = this.items;
    if (temp) {
      temp = temp.map((item) => {
        if (this.value) {
          item._checked = this.value.some((i) => {
            return i.id === item.id;
          });
        }
        return item;
      });
    }
    return temp;
  }


  handleClear() {
    const args = {
      sorting: this.sorting,
      filter: '',
      maxResultCount: this.pageSize,
      skipCount: 0,
      connectId: this.connectId,
    };
    this.emitChange(args);
  }

  handleClose(event, id: number) {
    let all = this.value.filter((item) => {
      return id !== item.id;
    });
    this.$emit('input', all);
  }

  handleSearch() {
    const args = {
      sorting: this.sorting,
      filter: this.filter,
      maxResultCount: this.pageSize,
      skipCount: 0,
      connectId: this.connectId,
    };
    this.emitChange(args);
  }


  selectAll(selection: any) {
    this.$emit('input', this.value.concat(selection.filter((item) => {
      return !this.value.some((i) => {
        return i.id === item.id;
      });
    })));
  }


  selectAllCancel(selection: any) {
    const unAll = this.items;
    this.$emit('input', unAll.concat(this.items).filter((item) => {
      return unAll.some((i) => {
        return i.id === item.id;
      }) && !this.items.some((j) => {
        return j.id === item.id;
      });
    }));
  }

  select(selection: any, row: any) {
    const find = this.value.find((item) => {
      return row.id === item.id;
    });
    const all = this.value;
    if (!find) {
      this.value.push(row);
    }
    this.$emit('input', all);
  }

  selectCancel(selection: any, row: any) {
    let all = this.value.filter((item) => {
      return row.id !== item.id;
    });
    this.$emit('input', all);
  }

  pageChange(page: number) {
    this.currentPage = page;
    const args = {
      sorting: this.sorting,
      filter: this.filter,
      maxResultCount: this.pageSize,
      skipCount: (this.currentPage - 1) * this.pageSize,
      connectId: this.connectId,
    };
    this.emitChange(args);
  }

  pageSizeChange(pageSize: number) {
  }

  rowClick(row: any, index: number) {
    if (!this.multiSelect) {
      let all = this.value;
      this.value.pop();
      this.value.push(row);
      this.$emit('input', all);
    } else {
      if (row._checked) {
        (this.$refs.table as any).$emit('on-select-cancel', null, row);
      } else {
        (this.$refs.table as any).$emit('on-select', null, row);
      }
    }
  }

  cellClick(row: any, column: any, data: any, event: any) {
    if (column.type === 'expand') {
      (this.$refs.table as any).$off('on-row-click');
    } else {
      (this.$refs.table as any).$on('on-row-click', this.rowClick);
    }
  }

  rowDblClick(row: any, index: number) {
    if (!this.multiSelect) {
      let all = this.value;
      this.value.pop();
      this.value.push(row);
      this.$emit('input', all);
      this.$emit('on-dblclick');
    }
  }

  rowClassName(row: any, index: number) {
    if (!this.multiSelect) {
      if (this.value.length === 1) {
        if (this.value[0].id === row.id) {
          return 'current-row';
        }
      }
    }
  }

  sortChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.sorting = sorting.key + ' ' + sorting.order;
      }
      const args = {
        sorting: this.sorting,
        filter: this.filter,
        maxResultCount: this.pageSize,
        skipCount: 0,
        connectId: this.connectId,
      };
      this.emitChange(args);
    }
  }



  emitChange(args) {
    if (this.optional) {
      for (const temp of this.optional) {
        args[temp.key] = temp.value;
      }
    }
    this.$emit('on-change', args);
  }

  @Watch('optional')
  optionalChange(newVal) {
    this.emitChange({
      sorting: this.sorting,
      filter: this.filter,
      maxResultCount: this.pageSize,
      skipCount: 0,
      connectId: this.connectId,
    });
  }


  mounted() {
    (this.$refs.table as any).$el.getElementsByClassName('ivu-table-body')[0].classList.add('beautiful-bar');
    (this.$refs.table as any).$el.getElementsByClassName('ivu-table-tip')[0].classList.add('beautiful-bar');
  }

}
</script>

<style lang="less" scoped>
#table_select::v-deep {
  .ivu-table-body {

    height: 339px;
    min-height: 339px;
    overflow-y: auto;
  }

  .ivu-table-tip {
    height: 339px;
    min-height: 339px;
    overflow-y: auto;
  }
}
</style>
